//
//  Navigator.swift
//  SwiftApp
//
//  Created by ak on 2019/3/12.
//  Copyright © 2019 ak. All rights reserved.
//
import UIKit

public class Navigator {
  public static let shared = Navigator()
  var routeMap: [String: String] = [:]
  var scheme: String = ""
  
  public func update(scheme: String, map: [String: String]) {
    self.scheme = scheme
    self.routeMap = self.routeMap.merging(map) { (origin, new) in new }
  }
}

public extension UINavigationController {
  
  func open(_ urlString: String) {
    if let vc = urlString.viewController() {
      self.pushViewController(vc, animated: true)
    }
  }
}

public extension String {
  
  func viewController() -> UIViewController? {
    if let url = URL(string: self.urlEncode()), let component = URLComponents(url: url, resolvingAgainstBaseURL: true), let scheme = url.scheme, let host = url.host {
      guard scheme == Navigator.shared.scheme else {
        dprint("实例化viewController失败，scheme不符合")
        return nil
      }
      if let vcName = Navigator.shared.routeMap[host], let vc = vcName.toUIViewController() {
        var params: [String: String?] = [:]
        component.queryItems?.forEach { item in
          params[item.name] = item.value
        }
        vc.setParams(params: params)
        dprint("实例化viewController \(self) -> \(vc)")
        return vc
      }
    }
    dprint("实例化viewController \(self) 失败")
    return nil
  }
}
